﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using intelliPaper.DB;
using intelliPaper.Model;

namespace intelliSys.Management.Automation.Profiler
{
    static class DataRepository
    {
        public static List<KnowledgePoint> KnowledgePoints;
        public static List<Question> Questions;
        public static List<Paper> Papers;
        public static void Load()
        {
            KnowledgePoints = Dao.GetAllKnowledgePoints();
            Questions = Dao.GetAllQuestions();
            Papers = Dao.GetAllPapers();
            Helper.InitialKnowledgePointInQuestions(KnowledgePoints, ref Questions);
            foreach (Question q in Questions)
            {
                q.NumericSummary = (int)CalculateErrorRate(q);
            }
            foreach (KnowledgePoint kp in KnowledgePoints)
            {
                kp.NumericSummary = (int)CalculateErrorRate(kp);
            }
            foreach (Paper p in Papers)
            {
                p.NumericSummary = (int)CalculateErrorRate(p);
            }
        }
        public static double CalculateErrorRate(object item)
        {
            double value = 0;
            if (item is Question)
            {
                Question taskitem = item as Question;
                try
                {
                    value = taskitem.HistoryMessages.Average<HistoryMessage>(o =>
                    {
                        return o.ErrorRate;
                    });
                }
                catch
                {
                }
            }
            if (item is KnowledgePoint)
            {
                KnowledgePoint kp = item as KnowledgePoint;
                try
                {
                    var cq = DataRepository.Questions.Where<Question>(o =>
                    {
                        return o.KnowledgePoints.Contains(kp);
                    }).Select<Question, double>(o =>
                    {
                        return o.HistoryMessages.Average<HistoryMessage>(hm =>
                        {
                            return hm.ErrorRate;
                        });
                    }).Average();
                }
                catch
                {
                }
            }
            if (item is Paper)
            {
                Paper p = item as Paper;
                try
                {
                    value = p.Questions.Select<Question, double>(o =>
                    {
                        return o.HistoryMessages.Average(hm =>
                        {
                            return hm.ErrorRate;
                        });
                    }).Average();
                }
                catch
                {
                }
            }
            return value;
        }
    }
}
